var $SohuNewsScope = window.$SohuNewsScope || {};
$SohuNewsScope.luckyDrawDraw = (function() {

    var documentAlias = document,
        encodeWrapper = encodeURIComponent,
        decodeWrapper = decodeURIComponent;

    var config = {
        prizeConfigAjaxUrl: '/api/activity/prizeConfig.go',
        prizeAjaxUrl: '/api/activity/prize.go',
        confirmAjaxUrl: '/api/activity/confirm.go',
        prizeLimitAjaxUrl: '/api/activity/prizeLimit.go'
        // prizeConfigAjaxUrl: 'http://testapi.k.sohu.com/api/activity/prizeConfig.go',
        // prizeAjaxUrl: 'http://testapi.k.sohu.com/api/activity/prize.go'
    };

    /*
     * Get cookie value
     */
    function _getCookie(cookieName) {
        var cookiePattern = new RegExp('(^|;)[ ]*' + cookieName + '=([^;]*)'),
            cookieMatch = cookiePattern.exec(documentAlias.cookie);

        return cookieMatch ? decodeWrapper(cookieMatch[2]) : 0;
    }

    /**
     * 用ras算法加密
     * @param  {String} publicKey 公钥
     * @param  {String} clearText 明文
     * @return {String}           密文
     */
    function _RSAEncryption(publicKey, clearText) {
        var encrypt = new JSEncrypt({
            default_key_size: 3072
        });
        encrypt.setKey(publicKey);
        var cipherText = encrypt.encrypt(clearText);
        return cipherText;
    }

    /**
     * 用ras算法解密
     * @param  {String} publicKey  公钥
     * @param  {String} cipherText 密文
     * @return {String}            明文
     */
    function _RSADecryption(publicKey, cipherText) {
        var decrypt = new JSEncrypt({
            default_key_size: 3072
        });
        decrypt.setKey(publicKey);
        var clearText = decrypt.decrypt(cipherText);
        return clearText;
    }

    /**
     * 根据p1取得公钥
     * @param  {String} p1           用户p1
     * @param  {Function} onSuccess  请求成功回调
     * @param  {Function} onError    请求失败回调
     * @param  {Function} onComplete 请求完成回调
     */
    function _getPublishKey(type, p1, onSuccess, onError, onComplete) {
        $SohuNewsScope.post(config.prizeConfigAjaxUrl, {
            p1: p1,
            type: type
        }, function(data) {
            if (data) {

                // 从cookie中读出加密、解密相关信息
                var key = _getCookie('key');
                var keycaptcha = _getCookie('keycaptcha');

                if (!!key && !!keycaptcha) {
                    if (onSuccess && typeof onSuccess === 'function') {
                        // 存入到返回的数据中
                        data.key = key;
                        data.keycaptcha = keycaptcha;
                        onSuccess(data);
                    }
                } else {
                    if (onError && typeof onError === 'function') {
                        onError();
                    }
                }
            } else {
                if (onError && typeof onError === 'function') {
                    onError();
                }
            }
        }, function() {
            if (onError && typeof onError === 'function') {
                onError();
            }
        }, function() {
            if (onComplete && typeof onComplete === 'function') {
                onComplete();
            }
        });
    }

    /**
     * 抽奖操作
     * @param  {String}   p1       用户p1
     * @param  {Function} callback 请求完成回调
     */
    function draw(type, p1, callback, onError) {
        // 现请求一个公钥
        _getPublishKey(type, p1, function(data) {
            var publicKey = data.key.toString().replace(/[\"\']/ig, '');
            // captcha 为手机校验码 可选
            // keycaptcha 加密的校验码 必选
            var prizeData = {
                keycaptcha: data.keycaptcha
            };
            // 将数据变成JSON字符串
            var prizeDataStr = JSON.stringify(prizeData);
            // 利用rsa加密
            var prizeDataCipherText = _RSAEncryption(publicKey, prizeDataStr);
            // base64后再
            // var prizeDataCipherBase64Text = _base64Encryption(prizeDataCipherText);

            $SohuNewsScope.post(config.prizeAjaxUrl, {
                p1: p1,
                type: type,
                crypt: prizeDataCipherText
            }, function(cipherTextData) {
                if (callback && typeof callback === 'function') {
                    callback(cipherTextData);
                }
            });
        }, function () {
            if (onError && typeof onError === 'function') {
                onError();
            }
        });
    }

    function _sendCofirmMsg(obj, callback) {

        var type = obj.type;
        var p1 = obj.p1;

        // 现请求一个公钥
        _getPublishKey(type, p1, function(data) {
            var publicKey = data.key.toString().replace(/[\"\']/ig, '');
            // captcha 为手机校验码 可选
            // keycaptcha 加密的校验码 必选
            obj.keycaptcha = data.keycaptcha;
            // 将数据变成JSON字符串
            var prizeDataStr = JSON.stringify(obj);
            // 利用rsa加密
            var prizeDataCipherText = _RSAEncryption(publicKey, prizeDataStr);
            // base64后再
            // var prizeDataCipherBase64Text = _base64Encryption(prizeDataCipherText);

            $SohuNewsScope.post(config.confirmAjaxUrl, {
                p1: p1,
                type: type,
                crypt: prizeDataCipherText
            }, function(cipherTextData) {
                if (callback && typeof callback === 'function') {
                    callback(cipherTextData);
                }
            });
        });
    }

    function _prizeLimit (obj, callback) {
        
        var type = obj.type;
        var p1 = obj.p1;

        // 现请求一个公钥
        _getPublishKey(type, p1, function(data) {
            var publicKey = data.key.toString().replace(/[\"\']/ig, '');
            // captcha 为手机校验码 可选
            // keycaptcha 加密的校验码 必选
            obj.keycaptcha = data.keycaptcha;
            // 将数据变成JSON字符串
            var prizeDataStr = JSON.stringify(obj);
            // 利用rsa加密
            var prizeDataCipherText = _RSAEncryption(publicKey, prizeDataStr);
            // base64后再
            // var prizeDataCipherBase64Text = _base64Encryption(prizeDataCipherText);

            $SohuNewsScope.post(config.prizeLimitAjaxUrl, {
                p1: p1,
                type: type,
                crypt: prizeDataCipherText
            }, function(cipherTextData) {
                if (callback && typeof callback === 'function') {
                    callback(cipherTextData);
                }
            });
        });
    }

    return {
        draw: draw,
        sendCofirmMsg: _sendCofirmMsg,
        prizeLimit: _prizeLimit
    };


}());

// $SohuNewsScope.luckyDraw.draw(3, 'NTcxODI0MzI3ODk1NzA1NjAxNw==', function (data) {
//     // console.log(data);
// });